package psoa.to.tptp.restful.resources;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;

public enum ShellUtil {
	;
	public static final String VKERNEL = "vkernel";
	public static final String VKERNELWRAPPER = "vkernelwrapper";
	public static final String ECHO = "echo";	
	public static final String RREDIRECT = "<";
	public static final String LPAREN = "(";
	public static final String RPAREN = ")";
	
	public static String rredirect(String s) {
		return RREDIRECT+s;
	}
	
	public static String subshell(String s) {
		return wrap(s,"(",")");
	}
	
	public static String wrap(String s, String head, String tail) {
		return head+s+tail;
	}
	
	public static DefaultExecuteResultHandler resultHandler() {
		return new DefaultExecuteResultHandler();
	}
	
	public static ExecuteWatchdog watchdog() {
		return new ExecuteWatchdog(60*1000);
	}
	
	public static Executor executor(ExecuteWatchdog dog) {
		Executor e = new DefaultExecutor();
		e.setWatchdog(dog);
		return e;
	}
	
	public static int execute(CommandLine cl, OutputStream out) throws ExecuteException, IOException {
		Executor e = executor(watchdog());
		PumpStreamHandler psh = new PumpStreamHandler(out,out);
		e.setStreamHandler(psh);
		return e.execute(cl);
	}
	
	public static CommandLine cl(String s) {
		return new CommandLine(s);
	}

	public static String echo(String s) {
		return ECHO+padl(s);
	}
	
	public static String padl(String s) {
		return " "+s;
	}
	
	public static String quote(String s) {
		return "\""+s+"\"";
	}
	
	public static String parenthesize(String s) {
		return LPAREN+s+RPAREN;
	}
}
